<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\UserToken;
use App\Models\WechatUser;
use Carbon\Carbon;
use App\Models\VerificationCode;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

/**
 * 微信小程序兑换码验证控制器
 * 用于处理微信小程序前端的兑换码验证请求
 */


/**
 * 验证码控制器
 * 用于处理微信小程序的验证码验证请求
 */
class VerifyCodeController extends Controller
{
    /**
     * 验证用户提供的验证码
     * 
     * 验证流程：
     * 1. 验证请求中是否包含必要的验证码
     * 2. 验证用户token是否有效
     * 3. 验证用户信息是否存在
     * 4. 验证验证码是否与存储的session_key匹配
     *
     * @param Request $request HTTP请求对象
     * @return \Illuminate\Http\JsonResponse 返回JSON格式的验证结果
     */
    public function verify(Request $request)
    {
        try {
            // 记录请求信息
            Log::info('收到验证兑换码请求', [
                'code' => $request->input('code'),
                'headers' => $request->header(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'request_time' => now()->toDateTimeString(),
                'request_method' => $request->method(),
                'request_path' => $request->path(),
                'full_url' => $request->fullUrl(),
                'all_parameters' => $request->all()
            ]);

            // 验证token
            $token = str_replace('Bearer ', '', $request->header('Authorization'));
            Log::info('Token验证', ['token' => $token]);
            
            if (empty($token)) {
                Log::warning('验证失败：Token为空');
                return response()->json([
                    'success' => false,
                    'message' => '请先登录'
                ], 401);
            }

            // 检查token
            $userToken = UserToken::where('token', $token)
                    ->where('expired_at', '>', Carbon::now())
                    ->first();
            
            Log::info('Token查询结果', [
                'token' => $token,
                'user_token' => $userToken ? $userToken->toArray() : null
            ]);

            if (!$userToken) {
                Log::warning('验证兑换码失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json([
                    'success' => false,
                    'message' => 'token已过期，请重新登录'
                ], 401);
            }

            // 原有的验证兑换码逻辑...
            $code = $request->input('code');

            // 查找兑换码，并关联活动和商品信息
            $verificationCode = VerificationCode::with(['codeActivity.product'])
                ->select([
                    'verification_codes.id',
                    'verification_codes.code',
                    'verification_codes.is_used',
                    'verification_codes.expired_at',
                    'verification_codes.value',
                    'verification_codes.code_activity_id'
                ])
                ->where('code', $code)
                ->first();

            Log::info('兑换码查询结果', [
                'input_code' => $code,
                'verification_code' => $verificationCode ? [
                    'code' => $verificationCode->code,
                    'is_used' => $verificationCode->is_used,
                    'expired_at' => $verificationCode->expired_at,
                    'value' => $verificationCode->value,
                    'activity' => $verificationCode->activity ? [
                        'id' => $verificationCode->activity->id,
                        'is_active' => $verificationCode->activity->is_active,
                        'product' => $verificationCode->activity->product ? [
                            'id' => $verificationCode->activity->product->id,
                            'name' => $verificationCode->activity->product->name
                        ] : null
                    ] : null
                ] : null
            ]);

            if (!$verificationCode) {
                return response()->json([
                    'success' => false,
                    'message' => '无效的兑换码'
                ]);
            }

            if ($verificationCode->is_used === VerificationCode::STATUS_USED) {
                return response()->json([
                    'success' => false,
                    'message' => '该兑换码已被使用'
                ]);
            }

            if ($verificationCode->expired_at && now()->gt($verificationCode->expired_at)) {
                return response()->json([
                    'success' => false,
                    'message' => '该兑换码已过期'
                ]);
            }

            if (!$verificationCode->codeActivity) {
                Log::warning('验证兑换码失败：未找到对应的活动', [
                    'code' => $code,
                    'verification_code_id' => $verificationCode->id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '无效的兑换活动'
                ]);
            }

            if (!$verificationCode->codeActivity->is_active) {
                return response()->json([
                    'success' => false,
                    'message' => '该活动已结束'
                ]);
            }

            // 获取商品信息和兑换码价值
            $product = $verificationCode->codeActivity->product;
            $price = $verificationCode->value;  // 从兑换码记录中获取价值

            if (!$product) {
                Log::warning('验证码验证失败：未找到对应商品', [
                    'code' => $code,
                    'activity_id' => $verificationCode->code_activity_id
                ]);
                return response()->json([
                    'valid' => false,
                    'message' => '未找到对应商品信息'
                ], 200);
            }

            // 验证通过，记录日志
            Log::info('验证码验证通过', [
                'user_id' => $userToken->wechat_user_id,
                'code' => $code,
                'product_name' => $product->name,
                'value' => $verificationCode->value,
                'created_at' => $verificationCode->created_at,
                'expired_at' => $verificationCode->expired_at
            ]);

            return response()->json([
                'valid' => true,
                'message' => '验证成功',
                'data' => [
                    'user_id' => $userToken->wechat_user_id,
                    'code' => $code,
                    'product_name' => $product->name,
                    'price' => $verificationCode->value,
                    'created_at' => $verificationCode->created_at,
                    'expired_at' => $verificationCode->expired_at
                ]
            ]);
        } catch (\Exception $e) {
            // 记录详细的错误信息
            Log::error('验证兑换码失败', [
                'error_message' => $e->getMessage(),
                'error_code' => $e->getCode(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine(),
                'stack_trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '验证失败，请稍后重试'
            ]);
        }
    }
}
